/**
  ******************************************************************************
  * File Name          : ltlx.c
  * Description        : 
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "tskcfg.h"
#include "bsp.h"
#include "ltlx.h"
#include "storage.h"
#include "route_base.h"
#include <string.h>

#define LTLX_STORAGE_ADDRESS      EEPROM_BLOCK00

LtLx_StorageParaType ltlx_storage_para;
const LtLx_ParaType LtLx_InitPara = 
{
	.lxtmen  = 0,
	.dummy1  = 0,
	.lxot    = 3600,
	
	.lxtm[0] = 0,
	.lxtm[1] = 0,
	.lxtm[2] = 0,
	.lxtm[3] = 0,
	.lxtm[4] = 0,
	.lxtm[5] = 0,
};

LtLx_ParaType LtLx_RunPara;

volatile LtLx_StateType LtLx_State = {0};
LtLx_StateType LtLx_State_last = {1};

uint8_t LtLx_ParaCheck(LtLx_ParaType *para)
{
  uint8_t i;
  
  if(para->lxot > 59940u)
  {
    return 1;
  }
  
  if((para->lxtmen != 0) && (para->lxtmen != 1))
  {
    return 2;
  }
  
  for(i=0; i<6; i++)
  {
    if(para->lxtm[i] > 86400)
    {
      return 3;
    }
  }
  
  return 0;
}

static void storage_save_initpara(void)
{
  memset(&ltlx_storage_para, 0, sizeof(LtLx_StorageParaType));
  
  ltlx_storage_para.para = LtLx_InitPara;
  
  ltlx_storage_para.crc16 = crc16((uint8_t *)&ltlx_storage_para.para, sizeof(LtLx_ParaType));
  
  eEPRom_Write(LTLX_STORAGE_ADDRESS, (const uint8_t*)&ltlx_storage_para, sizeof(LtLx_StorageParaType));
  
  LtLx_RunPara = LtLx_InitPara;
  
  printf("LtLx Init para saved!\r\n");
}

void Storage_xx_save(uint8_t type)
{
  memset(&ltlx_storage_para, 0, sizeof(LtLx_StorageParaType));
  
  ltlx_storage_para.para = LtLx_RunPara;
  
  ltlx_storage_para.crc16 = crc16((uint8_t *)&ltlx_storage_para.para, sizeof(LtLx_ParaType));
  
  eEPRom_Write(LTLX_STORAGE_ADDRESS, (const uint8_t*)&ltlx_storage_para, sizeof(LtLx_StorageParaType));
  
  printf("LtLx para save success.\r\n");
}

uint8_t Storage_xx_load(void)
{
  uint16_t crc;
  
  memset(&ltlx_storage_para, 0, sizeof(LtLx_StorageParaType));
  
  eEPRom_Read(LTLX_STORAGE_ADDRESS, (uint8_t*)&ltlx_storage_para, sizeof(LtLx_StorageParaType));
  
  crc = crc16((uint8_t *)&ltlx_storage_para.para, sizeof(LtLx_ParaType));
  
  if(ltlx_storage_para.crc16 != crc)
  {
    printf("crc check error:0x%04X, 0x%04X\r\n", ltlx_storage_para.crc16, crc);
    storage_save_initpara();
    return 1;
  }
  
  if(LtLx_ParaCheck(&ltlx_storage_para.para) != 0)
  {
    storage_save_initpara();
    return 2;
  }
  
  LtLx_RunPara = ltlx_storage_para.para;
  
  return 0;
}
